package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Animal;
import com.briup.pts.domain.bean.IndexRecord;
import com.briup.pts.mapper.AnimalMapper;
import com.briup.pts.mapper.IndexRecordMapper;
import com.briup.pts.service.IndexRecordService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class IndexRecordServiceImpl implements IndexRecordService {

    private final IndexRecordMapper recordMapper;
    private final AnimalMapper animalMapper;

    @Override
    @Transactional
    public void saveOrUpdate(IndexRecord indexRecord) {
        // 给某一个动物添加指标变化记录，所以必须保证该动物该存在，并且是处于养殖状态中
        String animalId = indexRecord.getIrdAnimalId();
        Animal animal = animalMapper.queryByIdWithStatus(animalId, "养殖中");
        if (animal == null) {
            throw new ServiceException(ResultCode.ANIMAL_IS_NOT_EXISTS);
        }

        // 如果该动物处于养殖状态，那么继续添加或修改指标数据
        if (indexRecord.getIrdId() != null) {
            // 如果传输的指标信息id不为null，那么表示修改，本项目中不建议修改指标记录数据
            throw new ServiceException(ResultCode.INDEX_RECORD_MODIFIED_IS_NOT_SUPPORT);
        }else {
            // 如果id为null，表示新增数据
            // animalId 和 时间与现有数据都一致，只有数据不一致，那么直接报错提示该时间点以及记录过数据
            // 确保同一个动物同一天只会记录一条指标数据
            IndexRecord indexRecord2 = recordMapper.queryByAnimalIdWithTime(
                    animalId,indexRecord.getIrdTime());
            if (indexRecord2 != null){
                throw new ServiceException(ResultCode.INDEX_RECORD_IS_EXISTS);
            }
            // 新增指标数据
            recordMapper.addIndexRecord(indexRecord);
        }
        // 同步修改动物表中对应的数据
        animal.setAHealthy(indexRecord.getIrdHealthy());
        animal.setAWeight(indexRecord.getIrdWeight());
        animalMapper.updateAnimal(animal);
    }

    @Override
    public PageInfo<IndexRecord> pageQuery(Integer pageNum, Integer pageSize,
                                           Integer startWeight, Integer endWeight) {
        try (Page<IndexRecord> ignored = PageHelper.startPage(pageNum,pageSize)){
            // 根据条件查询数据
            List<IndexRecord> records = recordMapper.queryByConditional(startWeight, endWeight);
            // 转换并返回数据
            Page<IndexRecord> recordPage = (Page<IndexRecord>) records;
            return new PageInfo<>(recordPage);
        }
    }

    @Override
    public void batchDelete(List<Integer> irIds) {
        recordMapper.batchDelete(irIds);
    }
}
